<template>
  <div class="app-content flex">
    <div class="h100 flex-column tree-left shrink0">
      <el-input class="mb10 tree-input" v-model="filterText" placeholder="请输入网关名称" clearable></el-input>
      <div class="card h0 flex1">
        <el-scrollbar class="h100">
          <el-radio-group style="display: block;" v-model="controllerNo" @change="handleControllerChange">
            <el-radio style="display: block;" v-for="(item,index) in controllerList" :key="index" :label="item.controllerName" :value="item.controllerNo">
              {{ item.controllerName }}
            </el-radio>
          </el-radio-group>
        </el-scrollbar>
      </div>
    </div>
    <div class="h100 flex1 flex-column w0">
      <div class="h50 flex-column">
        <div class="flex-alignc mb10">
          <el-select style="width: 200px" v-model="nodeId" filterable placeholder="请选择组件" @change="handleNodeIdChange">
            <el-option v-for="(item,index) in deviceList" :key="index" :label="item.logicAddress" :value="item.logicAddress" />
          </el-select>
          <el-checkbox-group class="ml10" v-model="echartsType" @change="handleEchartsTypeChange">
            <el-checkbox-button v-for="(item, index) in echartsTypeList" :key="index" :label="item.label" :value="item.value" />
          </el-checkbox-group>
          <div class="ml10">
            <el-date-picker
              style="width: 400px;"
              v-model="dateRange"
              :default-time="[new Date(2000, 1, 1, 3, 0, 0),new Date(2000, 1, 1, 21, 0, 0)]"
              value-format="YYYY-MM-DD HH:mm:ss"
              :clearable="false"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              @change="handleDateRangeChange"
            />
          </div>
        </div>
        <PowerEcharts :data="list" :option="echartsOption"></PowerEcharts>
      </div>
      <RichTable class="flex1" ref="richTableRef" :options="options"></RichTable>
    </div>
  </div>
</template>

<script setup>
import { stationPowerEchartsApi,deviceTreeListApi } from '@/api/station';
import ElectricEcharts from '@/components/Echart/ElectricEcharts'
import PowerEcharts from '@/components/Echart/PowerEcharts'
import TypeDate from '@/components/TypeDate'
import useUserStore from '@/store/modules/user'
import { onMounted } from 'vue';
const userStore = useUserStore()
const { proxy } = getCurrentInstance()


const controllerName = ref('')
const filterText = ref('')
const controllerList = computed(() => { // 网关列表
  return filterText.value?deviceTreeList.value.filter(item => item.controllerName.includes(filterText.value)):deviceTreeList.value
})

// 网关选择回调
const handleControllerChange = () => {
  let controllerItem = deviceTreeList.value.find(item => item.controllerNo==controllerNo.value)
  controllerName.value = controllerItem?.controllerName
  nodeId.value = controllerItem?.deviceList[0]?.logicAddress
  if(nodeId.value) {
    getPowerEcharts()
    richTableRef.value.initTable()
  }
  deviceList.value = controllerItem?controllerItem.deviceList:[]
}

// 组件列表
const deviceList = ref([])
// 组件选择回调
const handleNodeIdChange = () => {
  getPowerEcharts()
  richTableRef.value.initTable()
}
// const deviceList = computed(() => {
//   let controllerItem = deviceTreeList.value.find(item => item.controllerNo==controllerNo.value)
//   return controllerItem?controllerItem.deviceList:[]
// })

// 获取电站网关组件树形列表
const deviceTreeList = ref([])
const getDeviceTreeList = async () => {
  try {
    let res = await deviceTreeListApi({
      stationId:userStore.stationInfo.stationId
    })
    controllerNo.value = res.data[0]?.controllerNo
    controllerName.value = res.data[0]?.controllerName
    deviceTreeList.value = res.data
    handleControllerChange()
  }catch(err) {}
}

// 发电量报表列表
const richTableRef = ref();
const options = ref({
  download:true,
  downloadUrl:'/bopeng-cms/station/device/report/export',
  downloadName:'power',
  // 表格接口
  initRequest:false, // 初始化时接口是否自动请求数据
  tableRequest: {
    url: '/bopeng-cms/station/device/report/listPage',
    method: 'post',
    data: {
      controllerNo:'', // 网关编码
      nodeId:'', // 组件编码
      // date:'',
      // startTime:proxy.parseTime(new Date(), "{y}-{m}-{d} {h}:{i}:{s}"),
      startTime:proxy.parseTime(new Date(), "{y}-{m}-{d} ")+'03:00:00',
      endTime:proxy.parseTime(new Date(), "{y}-{m}-{d} ")+'21:00:00',
      stationId: userStore.stationInfo.stationId,
    }
  },
  column: [
    { prop: 'deviceName', label: '组件名称', },
    { prop: 'dateTime', label: '时间', },
    { prop: 'voltage', label: '实时电压(V)', },
    { prop: 'current', label: '实时电流(A)', },
    { prop: 'power', label: '实时功率(W)', },
    { prop: 'stationName', label: '所属电站', },
  ],
})
const { controllerNo, nodeId, startTime, endTime, type } = toRefs(options.value.tableRequest.data) // 保持响应式的解构

// 获取功率/电压/电流图表
const echartInfo = ref({
  current:[],
  power:[],
  voltage:[],
})
const list = ref([])
const getPowerEcharts = async () => {
  try {
    let res = await stationPowerEchartsApi(options.value.tableRequest.data)
    if(options.value.tableRequest.data.type==1) { // 日期类型日时,时间是时分格式
      res.data.forEach(item => {
        item.name = proxy.parseTime(item.name, "{h}:{i}")
      })
    }
    echartInfo.value = res.data
    handleEchartsTypeChange()
    // list.value = echartInfo.value[echartsType.value]
    // list.value = [
    //   {legendName:'功率(W)',list:echartInfo.value.power,color:'#679aff'},
    //   {legendName:'电压(V)',list:echartInfo.value.voltage,color:'#F6CA4E'},
    //   {legendName:'电流(A)',list:echartInfo.value.current,color:'#32C275'},
    // ]
  }catch(err) {}
}

// 图表类型
const echartsOption = ref({
  yAxis:{
    name: 'W',
    nameTextStyle: {
      align: 'right',
    },
    type: 'value',
    splitLine: {
      lineStyle: {
        type: 'dashed', //虚线
      },
      show: true //隐藏
    },
  }
})
const echartsType = ref(['power'])
const echartsTypeList = [
  { label:'功率', value:'power', unit:'W', color:'#679aff' },
  { label:'电压', value:'voltage', unit:'V', color:'#F6CA4E' },
  { label:'电流', value:'current', unit:'A', color:'#32C275' },
  // { label:'温度', value:'℃' },
]
// 图表类型改变回调
const handleEchartsTypeChange = () => {
  list.value = echartsType.value.map(item => {
    let echartsTypeItem = echartsTypeList.find(item1 => item1.value==item)
    return {
      legendName:`${echartsTypeItem.label}(${echartsTypeItem.unit})`,
      color:echartsTypeItem.color,
      unit:echartsTypeItem.unit,
      list:echartInfo.value[echartsTypeItem.value]
    }
  })
  echartsOption.value.yAxis.name = list.value.map(item => item.unit).join('/')
}

// 日期时间范围
let dateRange = computed({
  get() {
    return [startTime.value,endTime.value];
  },
  set(val) {
    startTime.value = val[0]
    endTime.value = val[1]
  },
});
// 时间范围改变回调
const handleDateRangeChange = () => {
  getPowerEcharts()
  richTableRef.value.initTable()
}
const disabledDate = (time) => { // 只能选择当前日期之前的日期
  return Date.now() < time.getTime();
}
onMounted(() => {
  getDeviceTreeList()
})
</script>

<style lang="scss" scoped>
.app-content {
  height: calc(100vh - 84px);
}
</style>
